<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OAEmail;
use App\Model\OAStaff;
use Illuminate\Http\Request;

class EmailLogic extends Controller
{
    public function sendEmail($input)
    {
        return OAEmail::query()->insertGetId(
            [
                'uid_from'=>$input['uid'],
                'uid_to'=>$input['uid_to'],
                'desc'=>$input['desc'],
                'pub_date'=>date('Y-m-d H:i:s'),
                'state'=>0,
                'file_path'=>$input['file_path'] ?? '',
            ]
        );

    }

    //获取聊天内容
    public function getChartContent($params)
    {
        //'uid_from'=>$params['uid_from'],'uid_to'=>$params['uid']
        $list = OAEmail::query()
            ->whereRaw("(uid_from = {$params['uid_from']} AND uid_to = {$params['uid']}) OR (uid_from = {$params['uid']} AND uid_to = {$params['uid_from']})")
            ->select()
            ->get()
            ->toArray();
        if(empty($list)) return [['class'=>'message frnd_message','desc'=>'...','is_img'=>0,'pub_date'=>date('Y-m-d H:i:s')]];

        $res = [];
        foreach ($list as &$val){
            $val['class'] = $val['uid_from'] == $params['uid'] ? 'message my_message' : 'message frnd_message';
            $val['is_img'] = 0;
            if($val['file_path']) $val['is_img'] = in_array(pathinfo($val['file_path'],PATHINFO_EXTENSION),['jpg','jpeg','gif','png']) ? 1 : 2;
            unset($val['uid_from'],$val['uid_to'],$val['id']);
            if(!$val['desc']) $val['desc'] = '-';
            if(!$val['is_img']) {
                unset($val['file_path']);
                $res[] = $val;
            }else{
                $res[] = [
                    'class'=>$val['class'],
                    'desc'=>$val['desc'],
                    'is_img'=>0,
                    'pub_date'=>$val['pub_date']
                ];
                $res[] = [
                    'class'=>$val['class'],
                    'is_img'=>$val['is_img'],
                    'pub_date'=>$val['pub_date'],
                    'file_path'=>$val['file_path'],
                ];
            }

        }

        return $res;
    }


    public function searchUser($input)
    {
        $staff = OAStaff::query()->where('username','like','%'.$input['username'].'%')->select(['id as uid_from','username as userFrom'])->get()->toArray();
        foreach ($staff as &$val){
            $val['desc'] = '...';
            $val['pub_date'] = date('Y-m-d H:i:s');
            $val['state'] = 0;
            $val['uid_to'] = $input['uid'];
        }
        return $staff;
    }
}
